import os
import re
import platform
import inspect
import logging
import subprocess
import gw_report_tool

logger = logging.getLogger('gw_file_system')

__CUR_DIR = os.getcwd()


def get_cur_dir():
    global __CUR_DIR
    ret_path = __CUR_DIR
    if platform.system() == 'Windows':
        ret_path = ret_path.decode('gbk')
    return ret_path

    caller_file = inspect.stack()[0][1]
    ret_path = os.path.abspath(os.path.dirname(caller_file))
    if platform.system() == 'Windows':
        ret_path = ret_path.decode('gbk')
    return ret_path


def get_full_path(filename):
    if os.path.isabs(filename):
        return filename
    dir_name = get_cur_dir()
    filename = os.path.join(dir_name, filename)
    filename = filename.replace('\\', '/')
    filename = re.sub('/+', '/', filename)
    return filename


def get_tool_path(filename):
    tool_path = ''
    if platform.system() == 'Darwin':
        tool_path = get_full_path('../tool/mac/' + filename)
    elif platform.system() == 'Linux':
        tool_path = get_full_path('../tool/linux/' + filename)
    else:
        tool_path = get_full_path('../tool/win/' + filename)
    return tool_path


def delete_file_folder(src):
    if os.path.exists(src):
        if os.path.isfile(src):
            try:
                src = src.replace('\\', '/')
                os.remove(src)
            except:
                pass

        elif os.path.isdir(src):
            for item in os.listdir(src):
                item_src = os.path.join(src, item)
                delete_file_folder(item_src)

            try:
                os.rmdir(src)
            except:
                pass


def copy_file_ignore_exist(source_file, target_file):
    source_file = get_full_path(source_file)
    target_file = get_full_path(target_file)
    if not os.path.exists(source_file):
        return
    if not os.path.exists(target_file) or os.path.exists(target_file) and os.path.getsize(target_file) != os.path.getsize(source_file):
        target_dir = os.path.dirname(target_file)
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)
        source_file_handle = open(source_file, 'rb')
        target_file_handle = open(target_file, 'wb')
        target_file_handle.write(source_file_handle.read())
        source_file_handle.close()
        target_file_handle.close()


def copy_file(source_file, target_file):
    source_file = get_full_path(source_file)
    target_file = get_full_path(target_file)

    if not os.path.exists(source_file):
        return 1
    if os.path.exists(target_file):
        os.remove(target_file)

    target_dir = os.path.dirname(target_file)
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    target_file_handle = open(target_file, 'wb')
    source_file_handle = open(source_file, 'rb')
    target_file_handle.write(source_file_handle.read())
    target_file_handle.close()
    source_file_handle.close()
    return 0


def modify_splash_start_activity(source, fileType, oldContent, newContent):
    if os.path.isdir(source):
        for file in os.listdir(source):
            sourceFile = os.path.join(source, file)
            modify_splash_start_activity(sourceFile, fileType, oldContent, newContent)

    elif os.path.isfile(source) and os.path.splitext(source)[1] == fileType:
        f = open(source, 'r+')
        data = str(f.read())
        f.close()
        bRet = False
        idx = data.find(oldContent)
        while idx != -1:
            data = data[:idx] + newContent + data[idx + len(oldContent):]
            idx = data.find(oldContent, idx + len(oldContent))
            bRet = True

        if bRet:
            fhandle = open(source, 'w')
            fhandle.write(data)
            fhandle.close()
            logger.info('modify file:%s' % source)
        else:
            logger.error('modify_splash_start_activity error')
            gw_report_tool.send_err_to_client(1019)


def copy_files(source_dir, target_dir):
    if not os.path.exists(source_dir) and not os.path.exists(target_dir):
        logger.error('copy files from %s to %s fail:file not found' % (source_dir, target_dir))
        return
    if os.path.isfile(source_dir):
        copy_file(source_dir, target_dir)
        return
    for file in os.listdir(source_dir):
        source_file = os.path.join(source_dir, file)
        target_file = os.path.join(target_dir, file)
        if os.path.isfile(source_file):
            if not os.path.exists(target_dir):
                os.makedirs(target_dir)
            if not os.path.exists(target_file) or os.path.exists(target_file) and os.path.getsize(target_file) != os.path.getsize(source_file):
                target_file_handle = open(target_file, 'wb')
                source_file_handle = open(source_file, 'rb')
                target_file_handle.write(source_file_handle.read())
                target_file_handle.close()
                source_file_handle.close()
        if os.path.isdir(source_file):
            copy_files(source_file, target_file)


def get_apk_sdk_version(apkFile):
    cmd = get_tool_path('aapt') + " d badging '" + apkFile + "'"
    cmd = cmd.replace('\\', '/')
    cmd = re.sub('/+', '/', cmd)
    cmd = str(cmd).encode('utf-8')
    ret = 0
    if platform.system() == 'Windows':
        st = subprocess.STARTUPINFO
        st.dwFlags = subprocess.STARTF_USESHOWWINDOW
        st.wShowWindow = subprocess.SW_HIDE
    s = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    info = s.communicate()[0]
    nPos = info.find('targetSdkVersion')
    nEnd = info.find("'", nPos + 18)
    sdkVersionName = info[nPos + 18:nEnd]
    return int(sdkVersionName)
